<template>
  <el-dialog
    class="base-dialog-root"
    :model-value="visible"
    width="40%"
    :title="formTitle"
    @close="onClose"
  >
    <el-form
      class="base-form-root"
      ref="ruleForm"
      :model="formModel"
      :rules="rules"
      label-position="top"
      size="large"
      @submit.prevent
      :disabled="formDisabled"
    >
      <el-form-item label="共享给" prop="members">
        <MemberSelect
          :multiple="true"
          :members="formModel.members"
          :options="cooperOptions"
          @select="handleMemberSelect"
          @change="handleMembersChange"
        >
        </MemberSelect>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="onClose">取消</el-button>
        <el-button type="primary" class="save-btn" @click="onConfirm" v-if="!formDisabled">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed, ref, shallowRef, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/src/message.scss'
import MemberSelect from './MemberSelect.vue'
import { termPurviewSave as saveCollaborator, termPurviewList as getCollaborator } from '@/management/api/dataform-extend'
import { type IMember, SurveyPermissions } from '@/management/utils/types/formsTypes'
import { CODE_MAP } from '@/management/api/eco/base'
const emit = defineEmits(['on-close-codify', 'onFocus', 'change', 'blur'])
const props = withDefaults(
  defineProps<{
    modifyId: string
    visible: boolean
  }>(),
  {
    modifyId: '',
    visible: false
  }
)
const ruleForm = shallowRef<any>(null)

const formTitle = ref('共享管理')

const cooperOptions: any = ref([])
onMounted(async () => {
  let resdata = [{
    "name": "编辑",
    "value": "SURVEY_CONF_MANAGE"
  },
  {
    "name": "删除",
    "value": "SURVEY_RESPONSE_MANAGE"
  },
  {
    "name": "共享",
    "value": "SURVEY_COOPERATION_MANAGE"
  }]
  cooperOptions.value = resdata.map((item: any) => {
    return {
      label: item.name,
      value: item.value
    }
  })
})

const formModel = ref({
  members: [] as IMember[]
})
watch(
  () => props.visible,
  async (val: boolean) => {
    if (val && props.modifyId) {
      try {
        const res: any = await getCollaborator({condition: {formId: props.modifyId}})
        if (res?.serverResult?.resultCode === CODE_MAP.SUCCESS) {
          formModel.value.members = res.data?.map((item: any) => {
            return {
              _id: item._id,
              userId: item.userId,
              username: item.username,
              role: item.permissions
            }
          })
        } else {
          formModel.value.members = []
          ElMessage.error(res?.serverResult?.resultMessage || '获取共享信息失败')
        }
      } catch (err) {
        ElMessage.error('获取共享信息接口请求错误')
      }
    }
  }
)
const rules = {
  members: [
    {
      trigger: 'change',
      validator: (rule: any, value: IMember[], callback: Function) => {
        if (value.length === 0) {
          callback('请至少添加一名共享者')
        }
        if (value.filter((item: IMember) => !item.role.length).length) {
          callback('请设置共享者对应权限')
        }
        if (
          value.filter(
            (item: IMember) =>
              item.role.length === 1 && item.role[0] === SurveyPermissions.CollaboratorManage
          ).length
        ) {
          callback('不能单独设置共享者管理')
        }
        callback()
      }
    }
  ]
}
const formDisabled = computed(() => {
  return false
})

const onClose = () => {
  emit('on-close-codify')
}
const onConfirm = async () => {
  ruleForm.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const collaborators = formModel.value.members.map((i: any) => {
          const collaborator = {
            objectId: i.userId,
            useLimit: i.role
          }
          if (i._id) {
            ;(collaborator as any)._id = i._id
          }
          return collaborator
        })
        const res: any = await saveCollaborator({
          formId: props.modifyId,
          collaborators
        })
        if (res?.serverResult?.resultCode === CODE_MAP.SUCCESS) {
          ElMessage.success('操作成功')
          emit('on-close-codify')
        } else {
          ElMessage.error(res?.serverResult?.resultMessage || '共享管理接口调用失败')
        }
      } catch (err) {
        ElMessage.error('createSpace status err' + err)
      }
    } else {
      return false
    }
  })
}

const handleMemberSelect = (val: string, label: string) => {
  formModel.value.members.push({
    userId: val,
    username: label,
    role: [
      SurveyPermissions.SurveyManage,
      SurveyPermissions.DataManage,
      SurveyPermissions.CollaboratorManage
    ]
  })
}
const handleMembersChange = (val: IMember[]) => {
  formModel.value.members = val
}
</script>

<style lang="scss" rel="lang/scss" scoped>
.base-form-root {
  padding: 20px;
}
</style>
